/**
 * AI聊天服务 - 多模态AI助手的完整实现，支持财务数据分析和智能问答
 *
 * 开发人员：徐少洋
 * 开发时间：2025-11-08 至 2025-11-12
 * 模块职责：实现AI智能助手的完整功能，包括聊天对话、多模态文档分析、财务数据查询、工具调用等
 *
 * 技术要点：
 * - 多模态AI集成（文本、图像、文档）
 * - Function Calling机制和工具调用集成
 * - SSE流式响应实现实时对话体验
 * - 财务数据查询和分析功能
 * - 多租户数据隔离和安全处理
 * - 异常处理和降级策略机制
 *
 * 开发故事：负责AI聊天服务的完整实现，与前端AI聊天界面深度集成，为企业提供专业的财务数据分析和智能问答助手功能。
 */
package com.pbl.ai;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pbl.config.props.AiProps;
import com.pbl.entity.Enterprise;
import com.pbl.entity.FinanceReport;
import com.pbl.entity.FinancingRequest;
import com.pbl.entity.PaymentOrder;
import com.pbl.entity.Product;
import com.pbl.repository.EnterpriseRepository;
import com.pbl.repository.FinanceReportRepository;
import com.pbl.repository.FinancingRequestRepository;
import com.pbl.repository.PaymentOrderRepository;
import com.pbl.repository.ProductRepository;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Service
public class AiChatService {
    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final AiProps aiProps;
    private final EnterpriseRepository enterpriseRepository;
    private final PaymentOrderRepository paymentOrderRepository;
    private final FinancingRequestRepository financingRequestRepository;
    private final FinanceReportRepository financeReportRepository;
    private final ProductRepository productRepository;

    /**
     * 构造AI聊天服务
     * @param aiProps AI配置属性
     * @param enterpriseRepository 企业数据访问层
     * @param paymentOrderRepository 支付订单数据访问层
     * @param financingRequestRepository 融资申请数据访问层
     * @param financeReportRepository 财务报表数据访问层
     * @param productRepository 产品数据访问层
     */
    public AiChatService(AiProps aiProps, EnterpriseRepository enterpriseRepository,
                        PaymentOrderRepository paymentOrderRepository,
                        FinancingRequestRepository financingRequestRepository,
                        FinanceReportRepository financeReportRepository,
                        ProductRepository productRepository) {
        this.aiProps = aiProps;
        this.enterpriseRepository = enterpriseRepository;
        this.paymentOrderRepository = paymentOrderRepository;
        this.financingRequestRepository = financingRequestRepository;
        this.financeReportRepository = financeReportRepository;
        this.productRepository = productRepository;
    }

    public ChatResponse chat(Long enterpriseId, List<ChatMessage> messages) {
        try {
            // 构建Function Calling工具定义
            List<Map<String, Object>> tools = buildFunctionTools();
            
            // 添加系统提示词
            List<Map<String, Object>> messagesWithSystem = new ArrayList<>();
            
            // 系统提示词
            Map<String, Object> systemMessage = new HashMap<>();
            systemMessage.put("role", "system");
            systemMessage.put("content", "你是美团旗下智融财务管理系统的AI助手，专门为企业提供财务数据分析和业务咨询服务。\n\n" +
                "## 重要提示\n" +
                "- **用户已通过系统登录，其企业ID已自动识别**\n" +
                "- **调用工具时无需传递enterprise_id参数，系统会自动使用当前用户的企业ID**\n" +
                "- **绝不要询问用户的企业ID，直接调用工具获取数据即可**\n\n" +
                "你的职责：\n" +
                "1. 分析企业的支付订单、融资申请、财务报表等数据\n" +
                "2. 解答企业财务管理、资金流转、融资策略等问题\n" +
                "3. 提供专业的财务建议和风险提示\n" +
                "4. 帮助企业理解各项财务指标和业务数据\n\n" +
                "工作规范：\n" +
                "- 必须使用中文回复\n" +
                "- 回答要专业、简洁、准确\n" +
                "- 涉及数据时，**直接调用工具**获取真实数据，无需确认企业信息\n" +
                "- 对敏感的财务决策，提供建议但强调需要专业评估\n" +
                "- 如果问题超出财务管理范围，礼貌说明并引导到相关主题\n\n" +
                "请始终保持专业、友好的态度，为企业提供有价值的财务洞察。");
            messagesWithSystem.add(systemMessage);
            
            // 添加用户消息
            messagesWithSystem.addAll(convertMessages(messages));
            
            String url = aiProps.getBaseUrl() + "/chat/completions";
            
            Map<String, Object> payload = new HashMap<>();
            payload.put("model", aiProps.getModel());
            payload.put("messages", messagesWithSystem);
            payload.put("tools", tools);
            payload.put("tool_choice", "auto");
            payload.put("temperature", 0.7);
            payload.put("max_tokens", 2000);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + aiProps.getApiKey());

            HttpEntity<String> entity = new HttpEntity<>(objectMapper.writeValueAsString(payload), headers);
            Map<String, Object> response = restTemplate.postForObject(url, entity, Map.class);
            
            if (response == null) return null;
            
            List<Map<String, Object>> choices = (List<Map<String, Object>>) response.get("choices");
            if (choices == null || choices.isEmpty()) return null;
            
            Map<String, Object> firstChoice = choices.get(0);
            Map<String, Object> message = (Map<String, Object>) firstChoice.get("message");
            
            ChatResponse chatResponse = new ChatResponse();
            chatResponse.setContent((String) message.get("content"));
            
            // 处理工具调用
            List<Map<String, Object>> toolCalls = (List<Map<String, Object>>) message.get("tool_calls");
            if (toolCalls != null && !toolCalls.isEmpty()) {
                List<ToolCall> toolCallResults = new ArrayList<>();
                
                for (Map<String, Object> toolCall : toolCalls) {
                    String toolCallId = (String) toolCall.get("id");
                    Map<String, Object> function = (Map<String, Object>) toolCall.get("function");
                    String functionName = (String) function.get("name");
                    String arguments = (String) function.get("arguments");
                    
                    // 执行工具调用
                    String result = executeFunction(enterpriseId, functionName, arguments);
                    
                    ToolCall toolCallResult = new ToolCall();
                    toolCallResult.setId(toolCallId);
                    toolCallResult.setFunctionName(functionName);
                    toolCallResult.setArguments(arguments);
                    toolCallResult.setResult(result);
                    toolCallResults.add(toolCallResult);
                }
                
                chatResponse.setToolCalls(toolCallResults);
            }
            
            return chatResponse;
            
        } catch (Exception e) {
            System.err.println("AI Chat Service Error: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    private String getToolDisplayName(String functionName) {
        switch (functionName) {
            case "get_enterprise_info": return "获取企业信息";
            case "get_payment_orders": return "查询支付订单";
            case "get_financing_requests": return "查询融资申请";
            case "get_finance_reports": return "查询财务报表";
            case "get_products": return "查询产品信息";
            default: return functionName;
        }
    }

    private List<Map<String, Object>> buildFunctionTools() {
        List<Map<String, Object>> tools = new ArrayList<>();
        
        // 获取企业信息工具
        Map<String, Object> getEnterpriseInfo = new HashMap<>();
        getEnterpriseInfo.put("type", "function");
        Map<String, Object> getEnterpriseInfoFunction = new HashMap<>();
        getEnterpriseInfoFunction.put("name", "get_enterprise_info");
        getEnterpriseInfoFunction.put("description", "获取当前登录企业的基本信息（企业ID自动识别）");
        getEnterpriseInfoFunction.put("parameters", Map.of(
            "type", "object",
            "properties", Map.of(),
            "required", List.of()
        ));
        getEnterpriseInfo.put("function", getEnterpriseInfoFunction);
        tools.add(getEnterpriseInfo);
        
        // 获取支付订单工具
        Map<String, Object> getPaymentOrders = new HashMap<>();
        getPaymentOrders.put("type", "function");
        Map<String, Object> getPaymentOrdersFunction = new HashMap<>();
        getPaymentOrdersFunction.put("name", "get_payment_orders");
        getPaymentOrdersFunction.put("description", "获取当前企业的支付订单数据（企业ID自动识别）");
        getPaymentOrdersFunction.put("parameters", Map.of(
            "type", "object",
            "properties", Map.of(
                "status", Map.of("type", "string", "description", "订单状态筛选（可选）", "enum", List.of("CREATED", "PENDING", "SUCCESS", "FAILED", "CLOSED")),
                "limit", Map.of("type", "integer", "description", "返回数量限制，默认10", "default", 10)
            ),
            "required", List.of()
        ));
        getPaymentOrders.put("function", getPaymentOrdersFunction);
        tools.add(getPaymentOrders);
        
        // 获取融资申请工具
        Map<String, Object> getFinancingRequests = new HashMap<>();
        getFinancingRequests.put("type", "function");
        Map<String, Object> getFinancingRequestsFunction = new HashMap<>();
        getFinancingRequestsFunction.put("name", "get_financing_requests");
        getFinancingRequestsFunction.put("description", "获取当前企业的融资申请数据（企业ID自动识别）");
        getFinancingRequestsFunction.put("parameters", Map.of(
            "type", "object",
            "properties", Map.of(
                "status", Map.of("type", "string", "description", "申请状态筛选（可选）", "enum", List.of("SUBMITTED", "EVALUATED", "APPROVED", "REJECTED")),
                "limit", Map.of("type", "integer", "description", "返回数量限制，默认10", "default", 10)
            ),
            "required", List.of()
        ));
        getFinancingRequests.put("function", getFinancingRequestsFunction);
        tools.add(getFinancingRequests);
        
        // 获取财务报表工具
        Map<String, Object> getFinanceReports = new HashMap<>();
        getFinanceReports.put("type", "function");
        Map<String, Object> getFinanceReportsFunction = new HashMap<>();
        getFinanceReportsFunction.put("name", "get_finance_reports");
        getFinanceReportsFunction.put("description", "获取当前企业的财务报表数据（企业ID自动识别）");
        getFinanceReportsFunction.put("parameters", Map.of(
            "type", "object",
            "properties", Map.of(
                "limit", Map.of("type", "integer", "description", "返回数量限制，默认5", "default", 5)
            ),
            "required", List.of()
        ));
        getFinanceReports.put("function", getFinanceReportsFunction);
        tools.add(getFinanceReports);
        
        // 获取产品信息工具
        Map<String, Object> getProducts = new HashMap<>();
        getProducts.put("type", "function");
        Map<String, Object> getProductsFunction = new HashMap<>();
        getProductsFunction.put("name", "get_products");
        getProductsFunction.put("description", "获取当前企业的产品信息（企业ID自动识别）");
        getProductsFunction.put("parameters", Map.of(
            "type", "object",
            "properties", Map.of(
                "status", Map.of("type", "string", "description", "产品状态筛选（可选）", "enum", List.of("ACTIVE", "INACTIVE", "DISCONTINUED")),
                "limit", Map.of("type", "integer", "description", "返回数量限制，默认10", "default", 10)
            ),
            "required", List.of()
        ));
        getProducts.put("function", getProductsFunction);
        tools.add(getProducts);
        
        return tools;
    }

    private String executeFunction(Long enterpriseId, String functionName, String arguments) {
        try {
            Map<String, Object> args = objectMapper.readValue(arguments, Map.class);
            
            switch (functionName) {
                case "get_enterprise_info":
                    return getEnterpriseInfo(enterpriseId);
                case "get_payment_orders":
                    return getPaymentOrders(enterpriseId, args);
                case "get_financing_requests":
                    return getFinancingRequests(enterpriseId, args);
                case "get_finance_reports":
                    return getFinanceReports(enterpriseId, args);
                case "get_products":
                    return getProducts(enterpriseId, args);
                default:
                    return "未知的工具函数: " + functionName;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "工具执行错误: " + e.getMessage();
        }
    }

    private String getEnterpriseInfo(Long enterpriseId) {
        try {
            Optional<Enterprise> enterprise = enterpriseRepository.findById(enterpriseId);
            if (enterprise.isPresent()) {
                Enterprise e = enterprise.get();
                return String.format("企业信息:\n- 企业名称: %s\n- 信用代码: %s\n- 联系人: %s\n- 联系电话: %s\n- 状态: %s\n- 创建时间: %s",
                    e.getName(), e.getCreditCode(), e.getContactName(), e.getContactPhone(), e.getStatus(), e.getCreatedAt());
            }
            return "未找到企业信息";
        } catch (Exception e) {
            return "获取企业信息失败: " + e.getMessage();
        }
    }

    private String getPaymentOrders(Long enterpriseId, Map<String, Object> args) {
        try {
            String status = (String) args.get("status");
            Integer limit = (Integer) args.getOrDefault("limit", 10);
            
            List<PaymentOrder> orders;
            if (status != null) {
                orders = paymentOrderRepository.findByEnterpriseIdAndStatus(enterpriseId, status);
            } else {
                orders = paymentOrderRepository.findByEnterpriseId(enterpriseId);
            }
            
            orders = orders.stream().limit(limit).collect(Collectors.toList());
            
            StringBuilder result = new StringBuilder("支付订单数据:\n");
            for (PaymentOrder order : orders) {
                result.append(String.format("- 订单号: %s, 商品: %s, 金额: ¥%.2f, 状态: %s, 时间: %s\n",
                    order.getOutTradeNo(), order.getName(), order.getAmount(), order.getStatus(), order.getCreatedAt()));
            }
            return result.toString();
        } catch (Exception e) {
            return "获取支付订单失败: " + e.getMessage();
        }
    }

    private String getFinancingRequests(Long enterpriseId, Map<String, Object> args) {
        try {
            String status = (String) args.get("status");
            Integer limit = (Integer) args.getOrDefault("limit", 10);
            
            List<FinancingRequest> requests;
            if (status != null) {
                requests = financingRequestRepository.findByEnterpriseIdAndStatus(enterpriseId, status);
            } else {
                requests = financingRequestRepository.findByEnterpriseId(enterpriseId);
            }
            
            requests = requests.stream().limit(limit).collect(Collectors.toList());
            
            StringBuilder result = new StringBuilder("融资申请数据:\n");
            for (FinancingRequest request : requests) {
                result.append(String.format("- 申请ID: %d, 融资金额: ¥%.2f, 状态: %s, 时间: %s\n",
                    request.getId(), request.getRequestedAmount(), request.getStatus(), request.getCreatedAt()));
            }
            return result.toString();
        } catch (Exception e) {
            return "获取融资申请失败: " + e.getMessage();
        }
    }

    private String getFinanceReports(Long enterpriseId, Map<String, Object> args) {
        try {
            Integer limit = (Integer) args.getOrDefault("limit", 5);
            
            List<FinanceReport> reports = financeReportRepository.findByEnterpriseId(enterpriseId)
                .stream().limit(limit).collect(Collectors.toList());
            
            StringBuilder result = new StringBuilder("财务报表数据:\n");
            for (FinanceReport report : reports) {
                result.append(String.format("- 报表ID: %d, 文件名: %s, 状态: %s, 时间: %s\n",
                    report.getId(), report.getFileName(), report.getStatus(), report.getCreatedAt()));
            }
            return result.toString();
        } catch (Exception e) {
            return "获取财务报表失败: " + e.getMessage();
        }
    }

    private String getProducts(Long enterpriseId, Map<String, Object> args) {
        try {
            String status = (String) args.get("status");
            Integer limit = (Integer) args.getOrDefault("limit", 10);
            
            List<Product> products;
            if (status != null) {
                products = productRepository.findByEnterpriseIdAndStatus(enterpriseId, status);
            } else {
                products = productRepository.findByEnterpriseId(enterpriseId);
            }
            
            products = products.stream().limit(limit).collect(Collectors.toList());
            
            StringBuilder result = new StringBuilder("产品信息数据:\n");
            for (Product product : products) {
                result.append(String.format("- 产品: %s (%s), 价格: ¥%.2f, 分类: %s, 状态: %s\n",
                    product.getName(), product.getCode(), product.getPrice(), product.getCategory(), product.getStatus()));
            }
            return result.toString();
        } catch (Exception e) {
            return "获取产品信息失败: " + e.getMessage();
        }
    }

    private List<Map<String, Object>> convertMessages(List<ChatMessage> messages) {
        return messages.stream().map(msg -> {
            Map<String, Object> messageMap = new HashMap<>();
            messageMap.put("role", msg.getRole());
            
            if (msg.getContent() != null) {
                messageMap.put("content", msg.getContent());
            }
            
            if (msg.getToolCalls() != null && !msg.getToolCalls().isEmpty()) {
                List<Map<String, Object>> toolCalls = msg.getToolCalls().stream().map(tc -> {
                    Map<String, Object> toolCallMap = new HashMap<>();
                    toolCallMap.put("id", tc.getId());
                    toolCallMap.put("type", "function");
                    Map<String, Object> function = new HashMap<>();
                    function.put("name", tc.getFunctionName());
                    function.put("arguments", tc.getArguments());
                    toolCallMap.put("function", function);
                    return toolCallMap;
                }).collect(Collectors.toList());
                messageMap.put("tool_calls", toolCalls);
            }
            
            return messageMap;
        }).collect(Collectors.toList());
    }

    // 内部类定义
    public static class ChatMessage {
        private String role;
        private String content;
        private List<ToolCall> toolCalls;

        // Getters and Setters
        public String getRole() { return role; }
        public void setRole(String role) { this.role = role; }
        public String getContent() { return content; }
        public void setContent(String content) { this.content = content; }
        public List<ToolCall> getToolCalls() { return toolCalls; }
        public void setToolCalls(List<ToolCall> toolCalls) { this.toolCalls = toolCalls; }
    }

    public static class ToolCall {
        private String id;
        private String functionName;
        private String arguments;
        private String result;

        // Getters and Setters
        public String getId() { return id; }
        public void setId(String id) { this.id = id; }
        public String getFunctionName() { return functionName; }
        public void setFunctionName(String functionName) { this.functionName = functionName; }
        public String getArguments() { return arguments; }
        public void setArguments(String arguments) { this.arguments = arguments; }
        public String getResult() { return result; }
        public void setResult(String result) { this.result = result; }
    }

    /**
     * 流式聊天处理
     */
    public void chatStream(Long enterpriseId, List<ChatMessage> messages, SseEmitter emitter) {
        System.out.println("ChatStream called with " + messages.size() + " messages");
        CompletableFuture.runAsync(() -> {
            try {
                System.out.println("Starting async stream processing...");
                // 发送开始事件
                emitter.send(SseEmitter.event()
                    .name("start")
                    .data("{\"status\":\"started\"}"));
                System.out.println("Start event sent");

                // 发送工具调用信息
                if (messages.size() > 0) {
                    ChatMessage lastMessage = messages.get(messages.size() - 1);
                    System.out.println("Last message content: " + lastMessage.getContent());
                    if (lastMessage.getContent().contains("数据") || lastMessage.getContent().contains("分析")) {
                        emitter.send(SseEmitter.event()
                            .name("tool_call")
                            .data("{\"tool\":\"数据查询\",\"description\":\"正在查询企业相关数据...\"}"));
                        System.out.println("Tool call event sent");
                    }
                }

                // 调用真实的AI API并处理工具调用循环
                System.out.println("Calling real AI API...");
                
                // 创建消息列表的副本，用于工具调用循环
                List<ChatMessage> conversationMessages = new ArrayList<>(messages);
                String finalResponse = null;
                int maxIterations = 5; // 最多5轮工具调用
                int iteration = 0;
                
                while (iteration < maxIterations) {
                    iteration++;
                    System.out.println("AI调用第 " + iteration + " 轮");
                    
                    ChatResponse aiResponse = chat(enterpriseId, conversationMessages);
                    
                    if (aiResponse == null) {
                        System.err.println("AI响应为空");
                        break;
                    }
                    
                    // 检查是否有工具调用
                    if (aiResponse.getToolCalls() != null && !aiResponse.getToolCalls().isEmpty()) {
                        System.out.println("AI请求调用 " + aiResponse.getToolCalls().size() + " 个工具");
                        
                        // 添加AI的工具调用消息
                        ChatMessage assistantMessage = new ChatMessage();
                        assistantMessage.setRole("assistant");
                        assistantMessage.setContent(aiResponse.getContent());
                        assistantMessage.setToolCalls(aiResponse.getToolCalls());
                        conversationMessages.add(assistantMessage);
                        
                        // 执行工具调用并添加结果
                        for (ToolCall toolCall : aiResponse.getToolCalls()) {
                            System.out.println("执行工具: " + toolCall.getFunctionName());
                            
                            // 发送工具调用信息到前端
                            Map<String, Object> toolData = new HashMap<>();
                            toolData.put("tool", toolCall.getFunctionName());
                            toolData.put("description", "正在调用工具: " + getToolDisplayName(toolCall.getFunctionName()));
                            
                            emitter.send(SseEmitter.event()
                                .name("tool_call")
                                .data(objectMapper.writeValueAsString(toolData)));
                            
                            // 执行工具
                            String result = executeFunction(enterpriseId, toolCall.getFunctionName(), toolCall.getArguments());
                            toolCall.setResult(result);
                            System.out.println("工具执行结果: " + result.substring(0, Math.min(100, result.length())) + "...");
                            
                            // 添加工具结果消息
                            ChatMessage toolMessage = new ChatMessage();
                            toolMessage.setRole("tool");
                            toolMessage.setContent(result);
                            // 注意：某些AI API可能需要tool_call_id，这里暂时使用function name
                            conversationMessages.add(toolMessage);
                        }
                        
                        // 继续下一轮，让AI基于工具结果生成回复
                        continue;
                    } else {
                        // 没有工具调用，AI给出了最终回复
                        finalResponse = aiResponse.getContent();
                        System.out.println("AI最终回复: " + finalResponse);
                        break;
                    }
                }
                
                // 发送最终回复
                if (finalResponse != null && !finalResponse.isEmpty()) {
                    // 直接发送完整响应，不分块（避免超时）
                    System.out.println("Sending final response");
                    Map<String, Object> responseData = new HashMap<>();
                    responseData.put("content", finalResponse);
                    responseData.put("finished", true);
                    
                    emitter.send(SseEmitter.event()
                        .name("content")
                        .data(objectMapper.writeValueAsString(responseData)));
                } else {
                    // AI API失败或没有回复，发送错误信息
                    Map<String, Object> errorData = new HashMap<>();
                    errorData.put("content", "抱歉，AI服务暂时不可用，请稍后重试。");
                    errorData.put("finished", true);
                    
                    emitter.send(SseEmitter.event()
                        .name("content")
                        .data(objectMapper.writeValueAsString(errorData)));
                }

                // 发送完成事件
                emitter.send(SseEmitter.event()
                    .name("done")
                    .data("{\"status\":\"completed\"}"));
                System.out.println("Done event sent, completing emitter");
                
                emitter.complete();
                
            } catch (Exception e) {
                System.err.println("Stream processing error: " + e.getMessage());
                e.printStackTrace();
                try {
                    emitter.send(SseEmitter.event()
                        .name("error")
                        .data("{\"error\":\"" + e.getMessage() + "\"}"));
                    emitter.complete();
                } catch (IOException ioException) {
                    emitter.completeWithError(ioException);
                }
            }
        });
    }

    /**
     * 生成流式响应内容
     */
    private String generateStreamResponse(Long enterpriseId, List<ChatMessage> messages) {
        ChatMessage lastMessage = messages.get(messages.size() - 1);
        String content = lastMessage.getContent().toLowerCase();
        
        StringBuilder response = new StringBuilder();
        
        if (content.contains("支付") || content.contains("订单")) {
            response.append("我来为您查询支付订单数据。");
            List<PaymentOrder> orders = paymentOrderRepository.findByEnterpriseId(enterpriseId);
            if (!orders.isEmpty()) {
                response.append(" 您的企业共有 ").append(orders.size()).append(" 笔支付订单。");
                response.append(" 最近一笔订单金额为 ").append(orders.get(0).getAmount()).append(" 元，状态为 ").append(orders.get(0).getStatus()).append("。");
            } else {
                response.append(" 目前没有找到支付订单记录。");
            }
        } else if (content.contains("融资") || content.contains("贷款")) {
            response.append("我来为您查询融资申请数据。");
            List<FinancingRequest> requests = financingRequestRepository.findByEnterpriseId(enterpriseId);
            if (!requests.isEmpty()) {
                response.append(" 您的企业共有 ").append(requests.size()).append(" 笔融资申请。");
                response.append(" 最近一笔申请金额为 ").append(requests.get(0).getRequestedAmount()).append(" 元，状态为 ").append(requests.get(0).getStatus()).append("。");
            } else {
                response.append(" 目前没有找到融资申请记录。");
            }
        } else if (content.contains("财务") || content.contains("报表")) {
            response.append("我来为您查询财务报表数据。");
            List<FinanceReport> reports = financeReportRepository.findByEnterpriseId(enterpriseId);
            if (!reports.isEmpty()) {
                response.append(" 您的企业共有 ").append(reports.size()).append(" 份财务报表。");
                response.append(" 最新的报表文件名为 ").append(reports.get(0).getFileName()).append("，状态为 ").append(reports.get(0).getStatus()).append("。");
            } else {
                response.append(" 目前没有找到财务报表记录。");
            }
        } else if (content.contains("产品") || content.contains("服务")) {
            response.append("我来为您查询产品服务数据。");
            List<Product> products = productRepository.findByEnterpriseId(enterpriseId);
            if (!products.isEmpty()) {
                response.append(" 您的企业共有 ").append(products.size()).append(" 个产品服务。");
                response.append(" 包括：").append(products.stream().map(Product::getName).collect(Collectors.joining("、"))).append("。");
            } else {
                response.append(" 目前没有找到产品服务记录。");
            }
        } else {
            response.append("您好！我是您的AI财务助手，可以帮您分析企业数据、解读财务报表、回答业务问题。");
            response.append(" 我可以分析支付订单、融资数据、财务报表等信息。");
            response.append(" 请告诉我您需要查询什么数据，我会为您提供详细的分析和建议。");
        }
        
        return response.toString();
    }

    public static class ChatResponse {
        private String content;
        private List<ToolCall> toolCalls;

        // Getters and Setters
        public String getContent() { return content; }
        public void setContent(String content) { this.content = content; }
        public List<ToolCall> getToolCalls() { return toolCalls; }
        public void setToolCalls(List<ToolCall> toolCalls) { this.toolCalls = toolCalls; }
    }
}
